import { InputNumber, Select, Input, Cascader, App, Switch, TimePicker, DatePicker } from 'antd';
// import { TextArea } from 'antd-mobile';
import React, {
  useEffect,
  useMemo,
  useState,
  useRef,
  forwardRef,
  useImperativeHandle,
} from 'react';

import { AppType } from '@/common/app/constants';
import useWindowWidth from '@/hooks/event/use-window-width';
import { useOrchestrationStore } from '@/store/orchestrationStore';
import { VariableItemType } from '@/types/app/type';
import { VariableInputEnum, WorkflowIOValueTypeEnum } from '@/types/workflow/constant';
import { cn } from '@/utils/common';

import QuestionTip from '../tooltip/QuestionTip';

const { TextArea } = Input;

export function VariableInputItem({
  item,
  variables,
  setVariables,
  inputRef,
  index,
}: {
  item: VariableItemType;
  variables: Record<string, any>;
  setVariables: (values: Record<string, any>) => void;
  inputRef?: React.RefObject<any>;
  index: number;
}) {
  const updateVariables = (value: any) => {
    setVariables({
      ...variables,
      [item.key]: value,
    });
  };

  return (
    <div className={`${index === 0 ? '' : 'mt-2'}`} key={item.id}>
      <div className="relative mb-1 flex w-full items-center">
        <div className="text-left text-sm font-semibold text-[#1D2129]">{item.label}</div>
        {item.required && <div className="font-bold text-error">*</div>}
        {item.description && <QuestionTip className="ml-1" title={item.description} />}
      </div>
      {item.type === VariableInputEnum.input && (
        <TextArea
          ref={inputRef}
          style={{
            maxHeight: '160px',
          }}
          autoSize
          value={variables[item.key]}
          maxLength={item.maxLength || 4000}
          onChange={(e) => {
            updateVariables(e.target.value);
          }}
          placeholder={item.description}
        />
      )}
      {item.type === VariableInputEnum.textarea && (
        <TextArea
          ref={inputRef}
          style={{
            maxHeight: '160px',
          }}
          value={variables[item.key]}
          onChange={(e) => {
            updateVariables(e.target.value);
          }}
          autoSize
          rows={5}
          maxLength={item.maxLength || 4000}
          placeholder={item.description}
        />
      )}

      {item.type === VariableInputEnum.select && (
        <Select
          ref={inputRef}
          style={{ width: '100%' }}
          options={(item.enums || []).map((item: { value: any }) => ({
            label: item.value,
            value: item.value,
          }))}
          value={variables[item.key]}
          placeholder={item.description}
          onChange={(e) => {
            updateVariables(e);
          }}
        />
      )}
      {item.type === VariableInputEnum.numberInput && (
        <InputNumber
          style={{
            width: '100%',
          }}
          ref={inputRef}
          step={1}
          {...(item.min !== undefined ? { min: item.min } : {})}
          {...(item.max !== undefined ? { max: item.max } : {})}
          value={variables[item.key]}
          onChange={(e) => {
            updateVariables(e);
          }}
          placeholder={item.description}
        />
      )}
      {item.type === VariableInputEnum.cascader && (
        <Cascader
          style={{
            width: '100%',
          }}
          ref={inputRef}
          value={variables[item.key]}
          onChange={(e) => {
            updateVariables(e);
          }}
          placeholder={item.description}
          options={item.enums}
        />
      )}
      {item.type === VariableInputEnum.switch && (
        <Switch
          ref={inputRef}
          value={variables[item.key]}
          onChange={(e) => {
            updateVariables(e);
          }}
        />
      )}
      {item.type === VariableInputEnum.time && (
        <>
          {item.valueType === WorkflowIOValueTypeEnum.time && (
            <TimePicker
              ref={inputRef}
              value={variables[item.key]}
              onChange={(e) => {
                updateVariables(e);
              }}
            />
          )}
          {(item.valueType === WorkflowIOValueTypeEnum.date ||
            item.valueType === WorkflowIOValueTypeEnum.datetime) && (
            <DatePicker
              ref={inputRef}
              value={variables[item.key]}
              showTime={item.valueType === WorkflowIOValueTypeEnum.datetime}
              onChange={(e) => {
                updateVariables(e);
              }}
            />
          )}
        </>
      )}
    </div>
  );
}

interface VariableInputRef {
  validateAndStart: () => boolean;
  checkCurrentPageRequired: () => boolean;
}

const VariableInput = forwardRef<
  VariableInputRef,
  {
    variables: Record<string, any>;
    variableList: VariableItemType[];
    chatStarted: boolean;
    setVariables: (values: Record<string, any>) => void;
    setChatStart: (value: boolean) => void;
    isFusionApp: boolean;
    currentPage: number;
    pageSize: number;
    className?: string;
  }
>(
  (
    {
      variables,
      variableList,
      chatStarted,
      setVariables,
      setChatStart,
      isFusionApp = false,
      currentPage,
      pageSize,
      className,
    },
    ref,
  ) => {
    const inputRefs = useRef<{ [key: string]: React.RefObject<any> }>({});
    const { message } = App.useApp();
    const { isPc } = useWindowWidth();

    // 获取当前页的变量项
    const totalItems = variableList.length;
    const totalPages = Math.ceil(totalItems / pageSize);
    const currentVariables = useMemo(() => {
      const startIndex = (currentPage - 1) * pageSize;
      const endIndex = Math.min(startIndex + pageSize, totalItems);
      return variableList.slice(startIndex, endIndex);
    }, [variableList, currentPage, pageSize, totalItems]);

    // 初始化每个输入项的ref
    useEffect(() => {
      variableList.forEach((variable) => {
        if (!inputRefs.current[variable.id]) {
          inputRefs.current[variable.id] = React.createRef();
        }
      });
    }, [variableList, variables]);

    const validateAndStart = () => {
      // 检查所有必填项
      const firstEmptyRequired = variableList.find(
        (variable) => variable.required && !variables[variable.key],
      );

      if (firstEmptyRequired) {
        message.warning(`请填写必填项【${firstEmptyRequired.label ?? firstEmptyRequired.key}】`);
        // 找到第一个空的必填项，聚焦它
        const ref = inputRefs.current[firstEmptyRequired.id];
        if (ref?.current) {
          ref.current.focus();
        }
        return false;
      }

      // 如果所有必填项都已填写，开始聊天
      setChatStart(true);
      return true;
    };

    // 检查当前页必填项是否都已填写
    const checkCurrentPageRequired = () => {
      return currentVariables.every((variable) => !variable.required || !!variables[variable.key]);
    };

    // 暴露 validateAndStart 和 checkCurrentPageRequired 方法给父组件
    useImperativeHandle(ref, () => ({
      validateAndStart,
      checkCurrentPageRequired,
    }));

    return (
      <div className={cn('py-2', className)}>
        <div className="text-left">
          <div
            className={`flex w-[${
              isPc ? '100%' : '100%'
            }] bg-transparent mx-auto flex-col rounded-md px-0 py-1`}
          >
            {currentVariables.map((value, index) => (
              <VariableInputItem
                key={value.id}
                index={index}
                item={value}
                variables={variables}
                setVariables={setVariables}
                inputRef={inputRefs.current[value.id]}
              />
            ))}
          </div>
        </div>
      </div>
    );
  },
);

export default VariableInput;

export const ChatBoxVariableInput = forwardRef<
  VariableInputRef,
  {
    chatStart: boolean;
    setChatStart: (value: boolean) => void;
    currentPage: number;
    pageSize: number;
  }
>(({ chatStart, setChatStart, currentPage, pageSize }, ref) => {
  const { workflow } = useOrchestrationStore();
  const {
    variables: flowVariables,
    setVariables: setVariablesStore,
    userSelectVariables,
    subAppDetail,
    appDetail,
  } = useOrchestrationStore();

  const [userSelectValue, setUserSelectValue] = useState<any>();

  const defaultValues = useMemo(() => {
    if (subAppDetail?.variables || subAppDetail?.workflow?.chatConfig?.variables) {
      const subAppVariables =
        subAppDetail?.variables?.length > 0
          ? subAppDetail?.variables
          : subAppDetail?.workflow?.chatConfig?.variables;
      setUserSelectValue(subAppVariables);
      return subAppVariables?.reduce((acc: Record<string, any>, item: any) => {
        acc[item.key] = item.defaultValue;
        return acc;
      }, {});
    }

    const userInputVariables = workflow?.chatConfig?.variables || userSelectVariables || [];
    setUserSelectValue(userInputVariables);

    return userInputVariables?.reduce((acc: Record<string, any>, item: any) => {
      acc[item.key] = item.defaultValue;
      return acc;
    }, {});
  }, [workflow?.chatConfig?.variables, userSelectVariables, subAppDetail]);

  useEffect(() => {
    setVariablesStore(defaultValues || {});
  }, [defaultValues, setVariablesStore]);

  return (
    <div>
      <div className="flex flex-col rounded-md bg-[transparent]">
        {/* <span className="text-left text-gray-600 font-normal text-sm">请先回答以下内容</span> */}
        <VariableInput
          ref={ref}
          chatStarted={chatStart}
          variableList={
            userSelectValue?.filter(
              (item: any) => item.type !== VariableInputEnum.custom && item?.required,
            ) || []
          }
          variables={flowVariables}
          setVariables={setVariablesStore}
          setChatStart={setChatStart}
          isFusionApp={appDetail?.appType === AppType.fusion}
          currentPage={currentPage}
          pageSize={pageSize}
        />
      </div>
    </div>
  );
});
